//
//  MDHDigitalKeyboard.swift
//  KeyBoard forKey
//
//  Created by Jack on 16/9/15.
//  Copyright © 2016年 Jack. All rights reserved.
//

import UIKit
private let marginvalue = CGFloat(0.5)
private let screenWith = UIScreen.main.bounds.size.width
private let defaultDoneColor = UIColor(red: 28 / 255, green: 171 / 255, blue: 235 / 255, alpha: 1)

public enum MDHDigitalKeyboardStyle {
    ///身份证键盘
    case idcard
    ///纯数字键盘
    case number
    ///小数点键盘
    case double
    ///Random 随机数键盘
    case random
}

public class MDHDigitalKeyboard: UIInputView {
    
    ///是否有小数点儿
    fileprivate var isHaveDian: Bool = false
    ///是否第一位是0
    fileprivate var isFirstZero: Bool = false
    ///是否是整数
    fileprivate var isInteger = false
    
    public static let `default` = MDHDigitalKeyboard(frame: CGRect(x: 0, y: 0, width: screenWith, height: 224), inputViewStyle: .keyboard)
    
    ///键盘的类型 默认是 身份证键盘
    public var style = MDHDigitalKeyboardStyle.idcard {
        didSet {
            setDigitButton(style: style)
        }
    }
    
    ///是否是 加密字符串
    fileprivate var isSafety: Bool = false {
        didSet {
            if isSafety {
                NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShowNotify(notifiction:)), name: UIResponder.keyboardWillShowNotification, object: nil)
            }
        }
    }
    
    ///是否高亮
    public var shouldHighlight = true {
        didSet {
            highlight(heghlight: shouldHighlight)
        }
    }
    
    ///修改确定按钮的 名字、字体颜色、背景颜色、点击事件
    public func customDoneButton(title: String, titleColor: UIColor = UIColor.white, theme: UIColor = UIColor(red: 28 / 255, green: 171 / 255, blue: 235 / 255, alpha: 1), target: Any? = nil, callback: Selector? = nil) {
        setDoneButton(title: title, titleColor: titleColor, theme: theme, target: target, callback: callback)
    }
    
    ///所有的textFields
    private var textFields = [UITextField]()
    ///父视图
    private weak var superView: UIView?
    ///所有的按钮
    private var buttions: [UIButton] = []
    
    public convenience init(_ view: UIView?, field: UITextField? = nil) {
        self.init(frame: CGRect.zero, inputViewStyle: .keyboard)
        addKeyboard(view, field: field)
    }
    private override init(frame: CGRect, inputViewStyle: UIInputView.Style) {
        let frameH = CGFloat(224)+kMMWPTFC().kSafeAreaBottom
        super.init(frame: CGRect(x: 0, y: 0, width: screenWith, height: frameH), inputViewStyle: inputViewStyle)
        backgroundColor = .white
    }
    
    public required init?(coder _: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    ///销毁视图
    deinit {
        self.deinit_view()
    }
    func deinit_view() -> () {
        self.superView = nil
        self.textFields.removeAll()
        self.buttions.removeAll()
    }
    
    ///添加 TextField
    public func addKeyboard(_ view: UIView?, field: UITextField? = nil) {
        superView = view
        customSubview()
        weak var weak_self = self
        if let textField = field {
            textFields.append(textField)
            textField.inputView = weak_self
            textField.delegate = weak_self
        } else {
            for view in (superView?.subviews)! {
                if view.isKind(of: UITextField.self) {
                    let textField = view as! UITextField
                    textField.delegate = weak_self
                    textField.inputView = weak_self
                    textFields.append(textField)
                }
            }
        }
    }
    
    ///创建Button
    private func customSubview() {
        var backSpace: UIImage?
        var dismiss: UIImage?
        let podBundle = Bundle(for: classForCoder)
        if let bundleURL = podBundle.url(forResource: "DigitalKeyboard", withExtension: "bundle") {
            if let bundle = Bundle(url: bundleURL) {
                backSpace = UIImage(named: "Keyboard_Backspace", in: bundle, compatibleWith: nil)
                dismiss = UIImage(named: "Keyboard_DismissKey", in: bundle, compatibleWith: nil)
            } else {
                backSpace = UIImage(named: "Keyboard_Backspace")
                dismiss = UIImage(named: "Keyboard_DismissKey")
            }
        } else {
            backSpace = UIImage(named: "Keyboard_Backspace")
            dismiss = UIImage(named: "Keyboard_DismissKey")
        }
        
        for idx in 0 ... 13 {
            let button = UIButton()
            button.titleLabel?.font = UIFont.systemFont(ofSize: 28)
            button.backgroundColor = UIColor.white
            button.tag = idx
            //button.borderColor = UIColor.lightGray
            //button.borderWidth = marginvalue
            highlight(heghlight: shouldHighlight)
            addSubview(button)
            button.setTitleColor(UIColor.black, for: .normal)
            switch idx {
            case 11://返回按钮
                button.setTitle("", for: .normal)
                button.setImage(dismiss, for: .normal)
            case 10:
                button.setTitle("0", for: .normal)
                buttions.append(button)
            case 9:///
                button.setTitle("X", for: .normal)
            case 12:
                button.setTitle("", for: .normal)
                button.setImage(backSpace, for: .normal)
            case 13:
                button.titleLabel?.font = UIFont.systemFont(ofSize: 17)
                button.backgroundColor = defaultDoneColor
                button.setTitleColor(UIColor.white, for: .normal)
                button.setBackgroundImage(nil, for: .normal)
                button.setBackgroundImage(nil, for: .highlighted)
                button.setTitle(LocalizedString(key: "Done"), for: .normal)
            default:
                button.setTitle("\(idx + 1)", for: .normal)
                buttions.append(button)
            }
            button.addTarget(self, action: #selector(tap), for: .touchUpInside)
        }
    }
    
    ///点击事件
    @objc func tap(sender: UIButton) {
        guard let text = sender.currentTitle else {
            fatalError("not found the sender's currentTitle")
        }
        let tf = firstResponder()
        
        switch sender.tag {
        case 12:
            tf?.deleteBackward()
        case 13, 11:
            tf?.resignFirstResponder()
        default:
            ///是否插入当前的数据
            var shouldInsertText = true
            if tf != nil {
                let beginning = tf?.beginningOfDocument ?? UITextPosition()
                let selectedRange = tf?.selectedTextRange
                let selectionStart = selectedRange?.start ?? UITextPosition()
                let selectionEnd = selectedRange?.end ?? UITextPosition()
                let location = tf?.offset(from: beginning, to: selectionStart) ?? 0//[self.textInput offsetFromPosition:beginning toPosition:selectionStart];
                let length = tf?.offset(from: beginning, to: selectionEnd) ?? 0
                let range = NSRange.init(location: location, length: length)
                
                if tf?.delegate?.responds(to: #selector(textField(_:shouldChangeCharactersIn:replacementString:))) ?? false {
                    shouldInsertText = tf?.delegate?.textField!(tf!, shouldChangeCharactersIn: range, replacementString: text) ?? true
                }
            }
            if shouldInsertText {
                tf?.insertText(text)
            }
        }
    }
    
    ///获取第一响应者
    func firstResponder() -> UITextField? {
        var firstResponder: UITextField?
        for field in textFields {
            if field.isFirstResponder {
                firstResponder = field
            }
        }
        return firstResponder
    }
    
    ///设置视图的布局
    public override func layoutSubviews() {
        super.layoutSubviews()
        ///高度
        let frameHeight = frame.height-kMMWPTFC().kSafeAreaBottom
        ///每个按钮的宽度
        let btn_w = frame.width/4
        ///右侧的两个按钮的高度
        let btn_r_h = frameHeight/2.0
        ///左侧的按钮高度
        let btn_l_h = frameHeight/4.0
        
        ///创建 分界线 的View
        let block_line_view = {
            [weak self] (frame1: CGRect) in
            DispatchQueue.main.async {
                let view_line1 = UIView()
                self?.addSubview(view_line1)
                view_line1.backgroundColor = UIColor.lightGray
                view_line1.frame = frame1
            }
        }
        
        for view in subviews {
            if view.isKind(of: UIButton.self) {
                let width = btn_w * 3
                let idx = view.tag
                if idx >= 12 {///删除键、确定键
                    view.frame = CGRect(x: width, y: CGFloat((idx - 12) % 2) * (btn_r_h), width: btn_w, height: btn_r_h)
                    if idx == 12 {
                        block_line_view(CGRect(x: width, y: btn_r_h, width: btn_w, height: marginvalue))
                    }else{
                        block_line_view(CGRect(x: 0, y: frameHeight, width: frame.width, height: marginvalue))
                    }
                } else {///左侧的其他按钮
                    let btn_l_y = CGFloat(idx / 3) * btn_l_h
                    view.frame = CGRect(x: CGFloat(idx % 3) * btn_w, y: btn_l_y, width: btn_w, height: btn_l_h)
                    if idx % 3 == 0 {
                        let rect1 = CGRect(x: 0, y: btn_l_y, width: width, height: marginvalue)
                        block_line_view(rect1)
                    }
                    if idx < 3 {
                        let rect1 = CGRect(x: CGFloat(idx+1)*btn_w, y: 0, width: marginvalue, height:  btn_l_h*4)
                        block_line_view(rect1)
                    }
                }
            }
        }
    }
    
    ///高亮
    func highlight(heghlight: Bool) {
        for view in subviews {
            if let button = view as? UIButton {
                if button.tag == 13 { return }
                if heghlight {
                    button.setBackgroundImage(UIImage.dk_image(with: .white), for: .normal)
                    button.setBackgroundImage(UIImage.dk_image(with: .lightGray), for: .highlighted)
                } else {
                    button.setBackgroundImage(UIImage.dk_image(with: .white), for: .normal)
                    button.setBackgroundImage(UIImage.dk_image(with: .white), for: .highlighted)
                }
            }
        }
    }
    
    ///
    func setDigitButton(style: MDHDigitalKeyboardStyle) {
        guard let button = findButton(by: 9) else {
            fatalError("not found the button with the tag")
        }
        button.setTitle("", for: .normal)
        switch style {
        case .idcard:
            button.setTitle("X", for: .normal)
        case .number:
            break
        case .double:
            let locale = Locale.current
            let decimalSeparator = locale.decimalSeparator! as String
            button.setTitle(decimalSeparator, for: .normal)
        case .random:
            self.isSafety = true
        }
    }
    
    ///查找 button
    func findButton(by tag: Int) -> UIButton? {
        for button in subviews {
            if button.tag == tag {
                return button as? UIButton
            }
        }
        return nil
    }
    
    func LocalizedString(key: String) -> String {
        /*if let bundle = Bundle(identifier: "com.apple.UIKit") {
            let key_value = bundle.localizedString(forKey: key, value: nil, table: nil)
            return key_value
        }
        return key*/
        return key
    }
    
    ///设置点击事件
    fileprivate func setDoneButton(title: String, titleColor: UIColor, theme: UIColor, target: Any?, callback: Selector?) {
        guard let itemButton = findButton(by: 13) else {
            fatalError("not found the button with the tag")
        }
        if let selector = callback, let target = target {
            itemButton.addTarget(target, action: selector, for: .touchUpInside)
        }
        itemButton.titleLabel?.font = UIFont.systemFont(ofSize: 17)
        itemButton.setTitle(title, for: .normal)
        itemButton.backgroundColor = theme
        itemButton.setTitleColor(titleColor, for: .normal)
    }
    
    ///随机数
    @objc func keyboardWillShowNotify(notifiction _: NSNotification) {
        titles = titles.sorted { _, _ in
            arc4random() < arc4random()
        }
        if !buttions.isEmpty {
            for (idx, item) in buttions.enumerated() {
                item.setTitle(titles[idx], for: .normal)
            }
        }
    }
    
    private lazy var titles = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
}

extension UIImage {
    public class func dk_image(with color: UIColor, size: CGSize = CGSize(width: 1, height: 1)) -> UIImage {
        UIGraphicsBeginImageContext(size)
        color.set()
        UIRectFill(CGRect(origin: CGPoint.zero, size: size))
        let image = UIGraphicsGetImageFromCurrentImageContext()!
        UIGraphicsEndImageContext()
        return image
    }
}

// MARK: UIInputViewAudioFeedback
extension MDHDigitalKeyboard: UIInputViewAudioFeedback {
    open var enableInputClicksWhenVisible: Bool {
        return true
    }
}


//MARK: - ====== UITextFieldDelegate ======= -
extension MDHDigitalKeyboard: UITextFieldDelegate {
    ///iOS最完美的UITextField中输入金额，只能输入数字和小数点，保留两位小数点且0放在首位
    public func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        if self.style == .double {
            let text = ((textField.text ?? "") as NSString)
            if self.isInteger {///必须是正整数
                if string.contains(".") {
                    return false
                }
                if text.length <= 0 && string == "0" {
                    return false
                }
            }
            if text.range(of: ".").location == NSNotFound {
                self.isHaveDian = false
            }
            if text.range(of: "0").location == NSNotFound {
                self.isFirstZero = false
            }
            
            let textStr = string as NSString
            
            if textStr.length > 0 {
                ///当前输入的字符
                let single = textStr.character(at: 0)
                let unichar0 = ("0" as NSString).character(at: 0)// unichar.init(0)
                let unichar9 = ("9" as NSString).character(at: 0)//unichar.init(9)
                let unichar_ = ("." as NSString).character(at: 0)
                
                ///数据格式正确
                if ((single >= unichar0 && single <= unichar9) || single == unichar_) {
                    if (text.length == 0) {
                        if (single == unichar_) {//首字母不能为小数点
                            return false;
                        }
                        if (single == unichar0 && !self.isInteger) {
                            self.isFirstZero = true;
                            return true;
                        }
                    }
                    
                    if (single == unichar_) {
                        ///text中还没有小数点
                        if(!self.isHaveDian) {
                            self.isHaveDian = true;
                            return true;
                        }else{
                            return false;
                        }
                    }else if (single == unichar0) {
                        if ((self.isFirstZero && self.isHaveDian) || (!self.isFirstZero && self.isHaveDian)) {
                            //首位有0有.（0.01）或首位没0有.（10200.00）可输入两位数的0
                            if text.isEqual(to: "0.0") {
                                return false
                            }
                            let ran = text.range(of: ".")
                            let tt = range.location - ran.location
                            if (tt <= 2) {
                                return true
                            }else{
                                return false
                            }
                        }else if (self.isFirstZero && !self.isHaveDian){
                            //首位有0没.不能再输入0
                            return false
                        }else{
                            return true
                        }
                    } else {
                        if (self.isHaveDian){
                            //存在小数点，保留两位小数
                            let ran = text.range(of: ".")
                            let tt = range.location - ran.location
                            
                            if (tt <= 2) {
                                return true
                            }else{
                                return false
                            }
                        }else if(self.isFirstZero && !self.isHaveDian) {
                            //首位有0没点
                            return false
                        }else{
                            return true
                        }
                    }
                }else{
                    //输入的数据格式不正确
                    return false
                }
            }else{
                return true
            }
        }
        return true;
    }
    
    func shouldChangeCharactersIn() -> () {
        
    }
    
    public func textFieldDidBeginEditing(_ textField: UITextField) {
        
    }
}







